<?php
/**
 * 单点登录工厂类，用于创建单点登录对象。
 *
 * @package K12SSO
 * @author Nio Xiao
 */
class K12SSO_Factory
{
    /**
     * 单点登录整合类型定义。
     */
    const TYPE_UAC = 'UAC';
    const TYPE_CAS = 'CAS';

    /**
     * 根据单点登录整合类型参数来创建单点登录对象。
     *
     * @param string $type 单点登录类型，参考常量 K12SSO_Factory::TYPE_XXX。
     * @param array $options 单点登录对象需要的参数设置数组。
     * @return K12SSO_Interface
     */
    public static function createInstance($type, $options = array())
    {
        $class = 'K12SSO_'.$type;
        $fn = dirname(__FILE__).'/'.$class.'.class.php';
        if (!file_exists($fn)) throw new Exception('未找到类文件 '.$class.'.class.php。');
        require_once $fn;
        if (!class_exists($class, false)) throw new Exception('未找到类 '.$class.'。');
        $instance = new $class($options);
        if (!$instance instanceof K12SSO_Interface) throw new Exception('类 '.$class.' 必须实现 K12SSO_Interface 接口');
        return $instance;
    }    

    /**
     * 获取服务器基础 URL。
     *
     * @return string
     */
    public static function getServerBaseUrl()
    {
        $base_url = '';
        if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) {
            $base_url = $_SERVER['HTTP_X_FORWARDED_HOST'];
        } else if (!empty($_SERVER['HTTP_X_FORWARDED_SERVER'])) {
            $base_url = $_SERVER['HTTP_X_FORWARDED_SERVER'];
        } else {
            if (empty($_SERVER['SERVER_NAME'])) {
                $base_url = $_SERVER['HTTP_HOST'];
            } else {
                $base_url = $_SERVER['SERVER_NAME'];
            }
        }
        $protocol = 'http';
        if (!strpos($base_url, ':')) {
            if ($_SERVER['SERVER_PORT'] == 443) {
                $protocol = 'https';
            } else if ($_SERVER['SERVER_PORT'] != 80) {
                $base_url .= ':';
                $base_url .= $_SERVER['SERVER_PORT'];
            }
        }
        return $protocol.'://'.$base_url;
    }
    
    /**
     * 获取完整的当前请求 URI。
     *
     * @return string
     */
    public static function getFullRequestUri()
    {
        return self::getServerBaseUrl().$_SERVER['REQUEST_URI'];
    }
    
    /**
     * 获取客户端地址。
     *
     * @return string
     */
    public static function getRemoteAddr()
    {
        $remote_addr = (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || $_SERVER['HTTP_X_FORWARDED_FOR'] == '127.0.0.1')
            ? $_SERVER['REMOTE_ADDR']
            : substr($_SERVER['HTTP_X_FORWARDED_FOR'], 0, strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ','));
        return trim($remote_addr);
    }
    
}
